import 'dart:io';
import 'dart:ui';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:mziot/app/config/constant.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/public_provider.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';

import '../controllers/auth_login_controller.dart';

class AuthLoginView extends GetView {
  @override
  // TODO: implement controller
  get controller => Get.put(AuthLoginController());

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text(LocaleKeys.public_app_name.tr),
          backgroundColor: Colors.transparent,
        ),
        body: Stack(
          children: [
            Image.asset(
              Assets.imagesListBack,
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover,
            ),
            Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 24.0.pixRatio),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Expanded(
                    child: ListView(
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      children: [
                        SizedBox(height: 32.0.pixRatio),
                        _logoView,
                        SizedBox(height: 20.0.pixRatio),
                        _titleView,
                        SizedBox(height: 30.0.pixRatio),
                        _typeView,
                        SizedBox(height: 5.0.pixRatio),
                        _textField(true),
                        SizedBox(height: 10.0.pixRatio),
                        _textField(false),
                        SizedBox(height: 30.0.pixRatio),
                        _loginButton,
                      ],
                    ),
                  ),
                  _thirdView,
                  SizedBox(height: 20.0.pixRatio),
                  _bottomView,
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  get _logoView {
    return GestureDetector(
      onTap: () {
        if (controller.isNext > 0 && controller.isNext < 10) {
          controller.isNext++;
          return;
        }
        controller.isNext++;
        Future.delayed(Duration(seconds: 1), () async {
          if (controller.isNext >= 5) {
            controller.isNext = 0;
            final env = GlobalConst.sharedPreferences?.getBool(Constant.env) ?? true;
            if (env) {
              showToast('develop');
              await GlobalConst.sharedPreferences?.setBool(Constant.env, false);
            } else {
              showToast('release');
              await GlobalConst.sharedPreferences?.setBool(Constant.env, true);
            }
            BlueService.share.stopScan();
            BlueService.share.disConnectDevice();
            GlobalConst.tempModel = null;
            await GlobalConst.sharedPreferences?.remove(Constant.kUser);
            AppPages.INITIAL();
          } else {
            controller.isNext = 0;
          }
        });
      },
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Container(
            width: 64,
            height: 64,
            color: Colors.white,
            child: Image.asset(Assets.imagesLogo),
          ),
        ),
      ),
    );
  }

  get _titleView {
    return Container(
      alignment: Alignment.center,
      child: Text(
        LocaleKeys.login_login.tr,
        style: MFont.semi_Bold24.apply(color: Colors.white),
      ),
    );
  }

  get _typeView {
    TextStyle defaultStyle = MFont.regular15.apply(color: Colors.white);
    TextStyle selectedStyle = MFont.semi_Bold17.apply(color: Colors.white);

    return Obx(() {
      bool isCode = (controller.loginType.value == LoginType.code) ? true : false;

      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              controller.loginType.value = LoginType.code;
              controller.codeController.text = '';
              controller.password.value = '';
            },
            child: Text(
              LocaleKeys.login_verify_login.tr,
              style: isCode ? selectedStyle : defaultStyle,
            ),
          ),
          SizedBox(width: 24),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              controller.loginType.value = LoginType.password;
              controller.codeController.text = '';
              controller.code.value = '';
            },
            child: Text(
              LocaleKeys.login_password_login.tr,
              style: isCode ? defaultStyle : selectedStyle,
            ),
          ),
        ],
      );
    });
  }

  Widget _textField(bool isEmail) {
    return Obx(() {
      bool isCode = (controller.loginType.value == LoginType.code) ? true : false;
      String hintText = '';
      var rightView;
      if (isEmail) {
        hintText = LocaleKeys.public_e_mail.tr;
        rightView = SizedBox();
      } else if (isCode) {
        hintText = LocaleKeys.public_verification_code.tr;
        rightView = _sendButton;
      } else {
        hintText = LocaleKeys.login_password.tr;
        rightView = _eyesButton;
      }

      return TextField(
        controller: isEmail ? controller.emailController : controller.codeController,
        obscureText: !isEmail && !isCode ? controller.isSee.value : false,
        cursorColor: Colors.white,
        style: MFont.semi_Bold15.apply(color: Colors.white),
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(bottom: 8),
          hintText: hintText,
          isDense: true,
          hintStyle: MFont.regular13.apply(color: Colors.white),
          labelStyle: MFont.semi_Bold15.apply(color: Colors.white),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.white, width: 0.7),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.white, width: 1),
          ),
          suffixIcon: rightView,
        ),
        textAlignVertical: TextAlignVertical.bottom,
        onChanged: (text) {
          if (isEmail) {
            controller.email.value = text;
          } else if (isCode) {
            controller.code.value = text;
          } else {
            controller.password.value = text;
          }
        },
      );
    });
  }

  get _sendButton {
    return UnconstrainedBox(
      child: TextButton(
        style: ButtonStyle(
          textStyle: MaterialStateProperty.all(MFont.regular13),
          foregroundColor: MaterialStateProperty.all(MColor.xFF333333),
          minimumSize: MaterialStateProperty.all(Size(10, 20)),
          visualDensity: VisualDensity.compact,
        ),
        onPressed: () => controller.takeCode(),
        child: Container(
          padding: EdgeInsets.only(top: 15),
          child: Obx(() {
            final time = controller.time.value;
            return Text(
              time == 61 ? LocaleKeys.public_send.tr : '$time s',
              style: MFont.regular13.apply(color: Colors.white),
              textAlign: TextAlign.right,
            );
          }),
        ),
      ),
    );
  }

  get _eyesButton {
    return IconButton(
      padding: EdgeInsets.only(top: 20),
      onPressed: () {
        controller.isSee.value = !controller.isSee.value;
      },
      icon: Obx(() {
        return Image.asset(
          controller.isSee.value ? Assets.imagesEyeOpen : Assets.imagesEyeClose,
          width: 20,
          height: 20,
          color: Colors.white,
        );
      }),
    );
  }

  get _loginButton {
    return Center(
      child: Container(
        width: 60,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(30),
          color: Colors.white,
        ),
        child: TextButton(
          style: ButtonStyle(shape: MaterialStateProperty.all(StadiumBorder())),
          onPressed: () {
            if (controller.isCheck.value) {
              controller.loginEmail();
            } else {
              showToast(
                  '${LocaleKeys.login_agreement.tr}${LocaleKeys.login_privacy.tr} & ${LocaleKeys.login_user.tr}');
            }
          },
          child: Icon(
            Icons.arrow_forward_rounded,
            size: 40,
            color: MColor.xFF48A23F_90,
          ),
        ),
      ),
    );
  }

  get _thirdView {
    Widget _thirdButton(String name, ThirdType type) {
      return IconButton(
        iconSize: 48.0.pixRatio,
        padding: EdgeInsets.zero,
        icon: Image.asset(name),
        onPressed: () {
          if (!controller.isCheck.value) {
            showToast(
                '${LocaleKeys.login_agreement.tr}${LocaleKeys.login_privacy.tr} & ${LocaleKeys.login_user.tr}');
            return;
          }
          if (type == ThirdType.ins) {
            controller.signInWithInstagram();
          } else if (type == ThirdType.facebook) {
            controller.signInWithFacebook();
          } else if (type == ThirdType.apple) {
            controller.signInWithApple();
          } else if (type == ThirdType.google) {
            controller.signInWithGoogle();
          }
        },
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        // _thirdButton(Assets.imagesIconIns, ThirdType.ins),
        _thirdButton(Assets.imagesIconFacebook, ThirdType.facebook),
        if (Platform.isIOS) ...{
          _thirdButton(Assets.imagesIconApple, ThirdType.apple),
        } else ...{
          _thirdButton(Assets.imagesIconGoogle, ThirdType.google),
        }
      ],
    );
  }

  get _bottomView {
    return SafeArea(
      top: false,
      child: Container(
        margin: EdgeInsets.only(bottom: 24.0.pixRatio),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            IconButton(
              iconSize: 12,
              padding: EdgeInsets.only(left: 6, right: 6, top: 4, bottom: 8),
              constraints: BoxConstraints(maxWidth: 24, maxHeight: 24),
              onPressed: () {
                controller.isCheck.value = !controller.isCheck.value;
              },
              icon: Obx(() {
                return Image.asset(
                  controller.isCheck.value ? Assets.imagesGouxuanSel : Assets.imagesGouxuanNor,
                  width: 12,
                  height: 12,
                );
              }),
            ),
            Expanded(
              child: RichText(
                text: TextSpan(
                  text: LocaleKeys.login_agreement.tr,
                  style: MFont.regular13.apply(color: Colors.white),
                  children: [
                    TextSpan(
                      text: LocaleKeys.login_privacy.tr.fixAutoLines(),
                      style: MFont.semi_Bold15.apply(color: Colors.white),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          Get.toNamed(
                            Routes.INSWEB,
                            parameters: {
                              'url': '${Server.web}protocol/privacy.html',
                              'title'
                                  '': LocaleKeys.login_privacy.tr
                            },
                          );
                        },
                    ),
                    TextSpan(
                      text: " & ",
                      style: MFont.regular13.apply(color: Colors.white),
                    ),
                    TextSpan(
                      text: LocaleKeys.login_user.tr,
                      style: MFont.semi_Bold15.apply(color: Colors.white),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          Get.toNamed(
                            Routes.INSWEB,
                            parameters: {
                              'url': '${Server.web}protocol/agreement.html',
                              'title'
                                  '': LocaleKeys.login_user.tr
                            },
                          );
                        },
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
